package com.xneure.utils.formatfile;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

public class HtmlParse {
	Document doc;

	public HtmlParse(String html) {
		doc = Jsoup.parse(html);
	}

	public HtmlParse(File file) {
		this(file, "utf-8");
	}

	public HtmlParse(File file, String charsetName) {
		try {
			doc = Jsoup.parse(file, charsetName);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Elements getElements(String nodePath) {
		return doc.select(nodePath);
	}

	public String getLabel(Element ele) {
		if (ele.attr("label").isEmpty() == false) {
			return ele.attr("label");
		} else {
			List<Node> childNodes = ele.childNodes();
			StringBuilder sb = new StringBuilder();
			for (int j = 0; j < childNodes.size(); j++) {
				Node node = childNodes.get(j);
				if (node instanceof TextNode) {
					sb.append(((TextNode) node).text());
				}
			}
			return sb.toString();
		}
	}

	public String[] getAttrs(String nodePath, String attrName) {
		List<Element> nodeList = getElements(nodePath);
		int size = nodeList.size();
		String[] attrs = new String[size];
		for (int i = 0; i < size; i++) {
			attrs[i] = nodeList.get(i).attr(attrName);
		}
		return attrs;
	}

	/**
	 * 解析参数
	 * 
	 * @param str
	 * @return Map<String,String>
	 */
	public Map<String, String> parseParam(String str) {
		String[] tmp = str.split("[(]|,|[)]");
		Map<String, String> paramMap = new LinkedHashMap<String, String>(tmp.length);
		for (String val : tmp) {
			if (val.contains("=")) {
				String[] split = val.split("=");
				paramMap.put(split[0].trim().toLowerCase(), split[1]);
			}
		}
		return paramMap;
	}
}
